package main

import (
    "fmt"
    "os"
    "time"
    "rpcserver/lib/thrift"
    "net"
    "rpcserver/service/rpcservice"
    "rpcserver/message"
    proto "github.com/golang/protobuf/proto"
)

const (
    HOST = "127.0.0.1"
    PORT = "9000"
)

func main() {
    startTime := currentTimeMillis()

    transportFactory := thrift.NewTFramedTransportFactory(thrift.NewTTransportFactory())
    protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()

    transport, err := thrift.NewTSocket(net.JoinHostPort(HOST, PORT))
    if err != nil {
        fmt.Fprintln(os.Stderr, "error resolving address:", err)
        os.Exit(1)
    }

    useTransport := transportFactory.GetTransport(transport)
    client := rpcservice.NewProtoRpcServiceClientFactory(useTransport, protocolFactory)
    if err := transport.Open(); err != nil {
        fmt.Fprintln(os.Stderr, "Error opening socket to "+HOST+":"+PORT, " ", err)
        os.Exit(1)
    }
    defer transport.Close()

    add_req := &message.ReqAdd{}
    add_req.Param1 = proto.Int32(10)
    add_req.Param2 = proto.Int32(12)

    content, err := proto.Marshal(add_req)
    if err != nil {
        fmt.Printf("marsh error = %s\n", err)
        return
    }

    request := rpcservice.NewProtoRequest()
    request.Type = 0
    request.Content = content

    response, err := client.ServeTwoWayMessage(request)
    if err != nil {
        fmt.Printf("Call Remote Error %s\n", err)
        return
    }

    if response.Ret != 0 {
        fmt.Printf("Call Remote Ret Code Failure = %d\n", response.Ret)
        return
    }

    res_add := &message.ResAdd{}
    err = proto.Unmarshal(response.Content, res_add)
    if err != nil {
        fmt.Printf("Ummarsh Response Error %s\n", err)
        return
    }

    fmt.Printf("RetVal = %d, Result = %d\n", res_add.GetRetval(), res_add.GetResult())

    endTime := currentTimeMillis()
    fmt.Printf("本次调用用时:%d-%d=%d毫秒\n", endTime, startTime, (endTime - startTime))
}

func currentTimeMillis() int64 {
    return time.Now().UnixNano() / 1000000
}
